package com.kotlin.tsw.usercenter.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.PersistableBundle
import android.util.Log
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhoto.TakeResultListener
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.InvokeParam
import com.jph.takephoto.model.TContextWrap
import com.jph.takephoto.model.TResult
import com.jph.takephoto.permission.InvokeListener
import com.jph.takephoto.permission.PermissionManager
import com.kotlin.base.utils.DateUtils
import com.kotlin.tsw.baselibrary.ext.onClick
import com.kotlin.tsw.baselibrary.ui.activity.BaseMVPActivity
import com.kotlin.tsw.usercenter.R
import com.kotlin.tsw.usercenter.injection.component.DaggerUserComponent
import com.kotlin.tsw.usercenter.injection.module.UserModule
import com.kotlin.tsw.usercenter.presenter.UserInfoPersenter
import com.kotlin.tsw.usercenter.presenter.view.UserInfoView
import kotlinx.android.synthetic.main.activity_user_info.*
import org.jetbrains.anko.toast
import java.io.File
import com.jph.takephoto.permission.TakePhotoInvocationHandler
import com.kotlin.base.utils.AppPrefsUtils
import com.kotlin.base.utils.GlideUtils
import com.kotlin.tsw.baselibrary.common.BaseConstant
import com.kotlin.tsw.providerlibrary.common.ProviderConstant
import com.kotlin.tsw.usercenter.data.protocol.UserInfo
import com.kotlin.tsw.usercenter.utils.UserPrefsUtils
import com.qiniu.android.http.ResponseInfo
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import org.json.JSONObject


class UserInfoActivity : BaseMVPActivity<UserInfoPersenter>(), UserInfoView, TakeResultListener, InvokeListener {
    private lateinit var mTakePhoto: TakePhoto
    private lateinit var mTempFile: File
    private lateinit var invokeParam: InvokeParam
    private val mUploadManager: UploadManager by lazy { UploadManager() }

    private var mLocalFile: String? = null
    private var mRemoteFile: String? = null

    private var mUserIcon: String? = null
    private var mUserName: String? = null
    private var mUserGender: String? = null
    private var mUserMobile: String? = null
    private var mUserSign: String? = null

    override fun injectComponent() {
        DaggerUserComponent.builder().activityComponent(activityComponent).userModule(UserModule()).build().inject(this)
        mPresenter.mView = this
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)
        mTakePhoto = getTakePhoto()
        mTakePhoto.onCreate(savedInstanceState)
        initView()
        initData()
    }


    /**
     * 获取TakePhoto实例
     * @return
     */
    fun getTakePhoto(): TakePhoto {
        mTakePhoto = TakePhotoInvocationHandler.of(this).bind(TakePhotoImpl(this, this)) as TakePhoto
        return mTakePhoto
    }

    private fun initView() {
        mUserIconView.onClick {
            AlertView("选择图片", null, "取消", null, arrayOf("拍照", "相册"),
                    this, AlertView.Style.ActionSheet, object : OnItemClickListener {
                override fun onItemClick(o: Any?, position: Int) {
                    mTakePhoto.onEnableCompress(CompressConfig.ofDefaultConfig(), false)
                    when (position) {
                        0 -> {
                            toast("拍照")
                            createTempFile()
                            mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
                        }
                        1 -> {
                            toast("相册")
                            mTakePhoto.onPickFromGallery()
                        }
                    }
                }
            }).show()
        }
        mHeaderBar.getRightTv().onClick {
//            mPresenter.editUser( mUserIcon!!, mUserName!!, mUserGender!!, mUserMobile!!, mUserSign!! )

            mUserIcon = mLocalFile?:""
            mUserName = mUserNameEt.text.toString()
            mUserGender = if(mGenderMaleRb.isChecked()) "0" else if(mGenderFemaleRb.isChecked()) "1" else "2"
            mUserSign = mUserSignEt.text.toString()
            UserPrefsUtils().putUserInfo(UserInfo( "123",mUserIcon!!, mUserName!!, mUserGender!!, mUserMobile!!, mUserSign!!))
            toast("保存成功")
        }
    }

    private fun initData() {
        mUserIcon = AppPrefsUtils.getString(ProviderConstant.KEY_USER_ICON)
        mUserName = AppPrefsUtils.getString(ProviderConstant.KEY_USER_NAME)
        mUserGender = AppPrefsUtils.getString(ProviderConstant.KEY_USER_GENDER)
        mUserMobile = if (AppPrefsUtils.getString(ProviderConstant.KEY_USER_MOBILE).equals("")) "13999999999" else AppPrefsUtils.getString(ProviderConstant.KEY_USER_MOBILE)
        mUserSign = AppPrefsUtils.getString(ProviderConstant.KEY_USER_SIGN)
        if (!mUserIcon.equals("")) {
            GlideUtils.loadUrlImage(this, mUserIcon!!, mUserIconIv)
        }
        if (mUserGender.equals("0")) {
            mGenderMaleRb.isChecked = true
        } else if (mUserGender.equals("1")) {
            mGenderFemaleRb.isChecked = true
        } else {
            mGenderMaleRb.isChecked = false
            mGenderFemaleRb.isChecked = false
        }
        if (mUserMobile.equals("")) {
            mUserMobileTv.setText("13999999999")
        }
        mUserMobileTv.setText(mUserMobile)
        if (mUserName.equals("")) mUserName = mUserMobile
        mUserNameEt.setText(mUserName)
        mUserSignEt.setText(mUserSign)

    }

    override fun takeSuccess(result: TResult?) {
        Log.d("takePhoto", "缓存路径：" + result?.image?.compressPath)
        Log.d("takePhoto", "原始路径：" + result?.image?.originalPath)
        mLocalFile = result?.image?.compressPath
//        mPresenter.getUploadToken()
        GlideUtils.loadUrlImage(this, mLocalFile!!, mUserIconIv)
    }

    override fun takeCancel() {
    }

    override fun takeFail(result: TResult?, msg: String?) {
        Log.d("takePhoto", msg.toString())
    }

    override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
        super.onSaveInstanceState(outState, outPersistentState)
        mTakePhoto.onSaveInstanceState(outState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mTakePhoto.onActivityResult(requestCode, resultCode, data)
    }

    fun createTempFile() {
        val tempFileName = "${DateUtils.curTime}.png"
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            this.mTempFile = File(Environment.getExternalStorageDirectory(), tempFileName)
            return
        }
        this.mTempFile = File(filesDir, tempFileName)
    }

    /**
     * runtime permissions
     * */
    override fun invoke(invokeParam: InvokeParam): PermissionManager.TPermissionType {
        val type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod())
        if (PermissionManager.TPermissionType.WAIT == type) {
            this.invokeParam = invokeParam
        }
        return type
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this)
    }

    override fun onGetUploadTokenResult(result: String) {
        mUploadManager.put(mLocalFile, null, result, object : UpCompletionHandler {
            override fun complete(key: String?, info: ResponseInfo?, response: JSONObject?) {
                mRemoteFile = BaseConstant.IMAGE_SERVER_ADDRESS + response?.get("hash")
                GlideUtils.loadUrlImage(this@UserInfoActivity, mRemoteFile!!, mUserIconIv)
            }
        }, null)
    }

    override fun onEditUserResult(result: UserInfo) {
        UserPrefsUtils().putUserInfo(result)
        toast("保存成功")
    }

}
